package com.ehome.poct.core.service.order;

import cn.hutool.core.bean.BeanUtil;
import com.ehome.paymentcenter.api.pay.BaseRspCO;
import com.ehome.poct.core.api.dto.order.UnificationPayReqDTO;
import com.ehome.poct.core.api.dto.order.UnificationShareAccountReqDTO;
import com.ehome.poct.core.api.virtual.TestOrderInternalPayService;
import com.ehome.poct.core.api.virtual.TestOrderUnificationPayService;
import com.ehome.poct.core.api.vo.order.PayChannelRespVO;
import com.ehome.poct.core.api.vo.order.UnificationPayVO;
import com.ehome.poct.core.api.vo.order.UnificationShareAccountVO;
import com.ehome.poct.core.constant.PayBizCodeEnums;
import com.ehome.poct.core.utils.EHomeAssert;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @auther: kuiba.peng
 * @date: 2022/11/21 21:06
 * @description:
 */
@Service
@RequiredArgsConstructor
public class TestOrderUnificationPayServiceImpl implements TestOrderUnificationPayService {

    private final TestOrderCombinationServiceImpl combinationService;

    @Resource
    private TestOrderInternalPayService orderInternalPayService;

    /**
     * 保存分账信息
     *
     * @param shareAccountReqDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public UnificationShareAccountVO saveShareAccount(UnificationShareAccountReqDTO shareAccountReqDTO) {
        if (shareAccountReqDTO.isOverwrite()) {
            combinationService.getUnificationPayRepository().delShareAccountByOrderNo(shareAccountReqDTO.getOrderNo());
        }
        return orderInternalPayService.saveShareAccount(shareAccountReqDTO.getOrderItemDTOList(), shareAccountReqDTO.getProfitDTOList(), shareAccountReqDTO.getClientId());
    }

    @Override
    public UnificationPayVO pay(UnificationPayReqDTO payReqDTO) {
        PayChannelRespVO<BaseRspCO> channelRespVO = combinationService.getPayFactory().pay(payReqDTO.getScanType(), payReqDTO);
        // 请求支付渠道失败
        EHomeAssert.isTrue(channelRespVO.isSuccess(), PayBizCodeEnums.PAY_CHANNEL_FAIL, channelRespVO.getMsg());
        UnificationPayVO.PayInfoDTO payInfoDTO = null;
        if (Objects.nonNull(channelRespVO.getData())) {
            payInfoDTO = BeanUtil.copyProperties(channelRespVO.getData(), UnificationPayVO.PayInfoDTO.class);
            // response不为空 并且channel不为空获取channelType ,否则return null
            Integer channelType = Optional.ofNullable(channelRespVO.getData())
                    .filter(baseRspCO -> Objects.nonNull(baseRspCO.getPayChannel()))
                    .map(baseRspCO -> baseRspCO.getPayChannel().getType()).orElse(null);
            payInfoDTO.setPayChannel(channelType);
        }
        return new UnificationPayVO().setPayInfo(payInfoDTO).setScanType(payReqDTO.getScanType());
    }
}
